package com.servlet;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Random;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@WebServlet("/servlet/ImgServlet")
public class ImgServlet extends HttpServlet {

	protected void doGet(HttpServletRequest request, 
				  HttpServletResponse response) 
	throws IOException, ServletException
	{
		BufferedImage img = 
				new BufferedImage(100, 40, BufferedImage.TYPE_INT_RGB);
		Color color = new Color(190, 250, 220);
		Graphics g = img.getGraphics();
		g.setColor(color);
		g.fillRect(0, 0, 100, 40);
		g.setFont(new Font("Roman", Font.PLAIN, 25));
		
		Random r = new Random();
		int num1 = r.nextInt(20);
		int num2 = r.nextInt(20);
		g.setColor(getRandomColor());
		g.drawString(num1 + "", 5, 30);
		g.setColor(getRandomColor());
		g.drawString("+", 35, 30);
		g.setColor(getRandomColor());
		g.drawString(num2 + "", 53, 30);
		g.setColor(getRandomColor());
		g.drawString("=", 85, 30);
		for(int i=0; i<10; ++i) {
			int x1 = r.nextInt(90);
			int y1 = r.nextInt(35);
			int x2 = r.nextInt(90);
			int y2 = r.nextInt(35);
			g.setColor(getRandomColor());
			g.drawLine(x1, y1, x2, y2);
		}
		int answer = num1 + num2;
		request.getSession().setAttribute("VerifyCode", answer);
		ImageIO.write(img, "JPEG", response.getOutputStream());
	}
	private Color getRandomColor() {
		Random r = new Random();
		return new Color(r.nextInt(100), r.nextInt(100), r.nextInt(100));
	}
}
